using FytSoa.Application.Crm.Param;
using FytSoa.Application.Erp;
using FytSoa.Common.Enum;
using FytSoa.Domain.Crm;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Result;
using FytSoa.Domain.Erp;
using Mapster;
using Masuit.Tools.Reflection;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Crm;

/// <summary>
/// 项目-合同管理服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v7")]
public class CrmContractService : IApplicationService 
{
    private readonly SugarRepository<CrmContract> _thisRepository;
    private readonly ErpFlowUseService _flowUseService;
    private readonly SugarRepository<CrmPayment> _paymentRepository;
    private readonly CrmOperateLogService _operateLogService;
    public CrmContractService(SugarRepository<CrmContract> thisRepository
        ,ErpFlowUseService flowUseService
        ,CrmOperateLogService operateLogService
        ,SugarRepository<CrmPayment> paymentRepository)
    {
        _thisRepository = thisRepository;
        _flowUseService = flowUseService;
        _operateLogService = operateLogService;
        _paymentRepository = paymentRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<CrmContractDto>> GetPagesAsync(CrmContractSearchParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Number.Contains(param.Key) || m.Name.Contains(param.Key))
            .WhereIF(param.CustomerId!=0,m=>m.CustomerId==param.CustomerId)
            .WhereIF(param.ProjectId!=0,m=>m.ProjectId==param.ProjectId)
            .Includes(m=>m.Customer)
            .Includes(m=>m.Project)
            .Includes(m=>m.TypeCode)
            .Includes(m=>m.SignEmployee)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        var result= query.Adapt<PageResult<CrmContractDto>>();
        if (result.TotalItems == 0) return result;
        var contractIds = result.Items.Select(m => m.Id);
        var contractList = await _paymentRepository.GetListAsync(m => contractIds.Contains(m.ContractId));
        foreach (var item in result.Items)
        {
            item.RefundAmount = contractList.Where(m=>m.ContractId==item.Id).Sum(m => m.Amount);
        }
        return result;
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<CrmContractDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.Customer)
            .Includes(m=>m.Project)
            .Includes(m=>m.TypeCode)
            .Includes(m=>m.Employee)
            .Includes(m=>m.SignEmployee)
            .FirstAsync(m=>m.Id==id);
        var result=model.Adapt<CrmContractDto>();
        result.Flow = await _flowUseService.GetFlowAsync(model.Id);
        return result;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(CrmContractDto model)
    {
        var toDay = await _thisRepository.CountAsync(m=>SqlFunc.DateIsSame(m.CreateTime,DateTime.Now));
        model.Number = "HT".ResNumber(toDay);
        var contractId= await _thisRepository.InsertReturnSnowflakeIdAsync(model.Adapt<CrmContract>());
        if (model.FlowId!=0)
        {
            await _flowUseService.AddAsync(new ErpFlowUseDto()
            {
                FlowId=model.FlowId,
                UseId=contractId,
                Type = FlowTypeEnum.Contract,
            });
        }
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = contractId,
            Type = (int)OaOperateEnum.Contract,
            Remark = "创建了合同信息"
        });
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyAsync(CrmContractDto model)
    {
        if (model.Status==CrmAuditEnum.NotReviewed)
        {
            await _flowUseService.ModifyAsync(new ErpFlowUseDto()
            {
                FlowId = model.FlowId,
                UseId = model.Id,
                Type = FlowTypeEnum.Contract,
            });
        }
        await _thisRepository.UpdateAsync(model.Adapt<CrmContract>());
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = model.Id,
            Type = (int)OaOperateEnum.Contract,
            Remark = "修改了合同信息"
        });
    }
    
    /// <summary>
    /// 修改状态
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyStatusAsync(CrmContractStatusParam model)
    {
        await _thisRepository.UpdateAsync(m=>new CrmContract()
        {
            Status = model.Status
        },m=>model.Id.Contains(m.Id));
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateIds = model.Id,
            Type = (int)OaOperateEnum.Contract,
            Remark = "变更了合同状态为："+model.Status.GetDescription()
        });
        if (model.Status==CrmAuditEnum.InReview)
        {
            foreach (var item in model.Id)
            {
                await _flowUseService.StartAuditAsync(item, FlowTypeEnum.Contract);
            }
        }
    }
    
    /// <summary>
    /// 修改状态
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyFileAsync(CrmContractFilesParam model)
    {
        var contract = await _thisRepository.GetFirstAsync(m => m.Id == model.Id);
        contract.Files.Add(model.File);
        await _thisRepository.UpdateAsync(contract);
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = model.Id,
            Type = (int)OaOperateEnum.Contract,
            Remark = "更新了合同的附件信息"
        });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task DeleteAsync([FromBody] List<long> ids)
    {
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
        await _flowUseService.DeleteAsync(ids);
    }

}
